import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:keyboard_avoider/keyboard_avoider.dart';
import 'model.dart';

var gItem = {
  'id': '',
  'website': '',
  'weblink': '',
  'username': '',
  'passwordText': '',
  'password': '',
  'email': '',
  'remark': ''
};

class AddCode extends StatelessWidget {
  final Post item;
  const AddCode({Key key, this.item}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    if (item != null) {
      gItem['website'] = item.website;
      gItem['weblink'] = item.weblink;
      gItem['username'] = item.username;
      gItem['passwordText'] = item.passwordText;
      gItem['password'] = item.password;
      gItem['email'] = item.email;
      gItem['remark'] = item.remark;
      gItem['id'] = item.id;
    }
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: Text(gItem['id'] == '' ? '添加密码' : '编辑密码'),
        elevation: 0.0,
      ),
      body: Theme(
        data: Theme.of(context).copyWith(
          primaryColor: Colors.black,
        ),
        child: Container(padding: EdgeInsets.all(16.0), child: AddCodeForm()),
      ),
    );
  }
}

class AddCodeForm extends StatefulWidget {
  @override
  AddCodeFormState createState() => AddCodeFormState();
}

class AddCodeFormState extends State<AddCodeForm> {
  final registerFormKey = GlobalKey<FormState>();
  String website = gItem['website'],
      weblink = gItem['weblink'],
      username = gItem['username'],
      passwordText = gItem['passwordText'],
      password = gItem['password'],
      email = gItem['email'],
      remark = gItem['remark'];
  bool autovalidate = false;
  void submitRegisterForm() {
    if (registerFormKey.currentState.validate()) {
      registerFormKey.currentState.save();
      this.fetchPosts(
          website, weblink, username, passwordText, password, email, remark);
      EasyLoading.show(
          status: 'loading...', maskType: EasyLoadingMaskType.black);
    } else {
      setState(() {
        autovalidate = true;
      });
    }
  }

  String validateWebsite(value) {
    if (value.isEmpty) {
      return '网站名是必填项！';
    }
    return null;
  }

  String validateUsername(value) {
    if (value.isEmpty) {
      return '用户名是必填项！';
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    return KeyboardAvoider(
        autoScroll: true,
        child: Form(
            key: registerFormKey,
            child: Column(
              children: <Widget>[
                TextFormField(
                    initialValue: website,
                    decoration: InputDecoration(
                      labelText: '网站名',
                      helperText: '',
                    ),
                    onSaved: (value) {
                      website = value;
                    },
                    validator: validateWebsite),
                TextFormField(
                    initialValue: weblink,
                    decoration: InputDecoration(
                      labelText: '网站连接',
                      helperText: '',
                    ),
                    onSaved: (value) {
                      weblink = value;
                    }),
                TextFormField(
                    initialValue: username,
                    decoration: InputDecoration(
                      labelText: '用户名',
                      helperText: '',
                    ),
                    onSaved: (value) {
                      username = value;
                    },
                    validator: validateUsername),
                TextFormField(
                    initialValue: passwordText,
                    decoration: InputDecoration(
                      labelText: '密码提示',
                      helperText: '',
                    ),
                    onSaved: (value) {
                      passwordText = value;
                    }),
                TextFormField(
                    initialValue: password,
                    decoration: InputDecoration(
                      labelText: '密码',
                      helperText: '',
                    ),
                    onSaved: (value) {
                      password = value;
                    }),
                TextFormField(
                    keyboardType: TextInputType.emailAddress,
                    initialValue: email,
                    decoration: InputDecoration(
                      labelText: '邮箱',
                      helperText: '',
                    ),
                    onSaved: (value) {
                      email = value;
                    }),
                TextFormField(
                    keyboardType: TextInputType.multiline,
                    maxLines: null,
                    initialValue: remark,
                    decoration: InputDecoration(
                      labelText: '备注',
                      helperText: '',
                    ),
                    onSaved: (value) {
                      remark = value;
                    }),
                SizedBox(
                  height: 32.0,
                ),
                Container(
                  width: double.infinity,
                  child: ElevatedButton(
                    style: ButtonStyle(
                        // foregroundColor: Theme.of(context).accentColor, //字体颜色
                        elevation: MaterialStateProperty.all(0)),
                    child: Text('提交', style: TextStyle(color: Colors.white)),
                    onPressed: submitRegisterForm,
                  ),
                ),
              ],
            )));
  }

  Future fetchPosts($website, $weblink, $username, $passwordText, $password,
      $email, $remark) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var dataBody = jsonEncode({
      'id': gItem['id'] != '' ? gItem['id'] : '',
      'website': $website,
      'weblink': $weblink,
      'username': $username,
      'passwordText': $passwordText,
      'password': $password,
      'email': $email,
      'remark': $remark
    });
    print(dataBody);
    final response = await http.post('https://me.yuanqiao.pw/api/me/insert.php',
        body: dataBody,
        headers: {HttpHeaders.authorizationHeader: prefs.get('user_token')});
    EasyLoading.dismiss();
    if (response.statusCode == 200) {
      gItem['id'] = '';
      gItem['website'] = '';
      gItem['weblink'] = '';
      gItem['username'] = '';
      gItem['passwordText'] = '';
      gItem['password'] = '';
      gItem['email'] = '';
      gItem['remark'] = '';
      final responseBody = json.decode(response.body);
      print('responseBody');
      print(responseBody);
      Fluttertoast.showToast(
          msg: responseBody['error'],
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.white,
          textColor: Colors.black87,
          fontSize: 16.0);
      Navigator.of(context).pushNamed('/home');
    } else {
      Fluttertoast.showToast(
          msg: '网络或服务器错误',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.white,
          textColor: Colors.black87,
          fontSize: 16.0);
    }
  }
}
